package com.kye.addrpicker.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.kye.addrpicker.model.City;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class DBManager {
    private static final String ASSETS_NAME = "china_cities.db";
    private static final String DB_NAME = "china_cities.db";
    private static final String TABLE_NAME = "cityDatas";
    private static final String UNIQUEID = "uniqueID";
    private static final String FULLNAME = "FullName";
    private static final String FULLPY = "FullPY";
    private static final String STARTPY = "StartPY";
    private static final String PARENTID = "ParentID";
    private static final String LEVELTYPE = "LevelType";
    private static final String STATUS = "status";
    private static final String FLAG = "flag";
    private static final String WDFLAG = "wdflag";
    private static final String ALLFLAG = "allflag";
    private static final int BUFFER_SIZE = 1024;
    private String DB_PATH;
    private Context mContext;

    public DBManager(Context context) {
        this.mContext = context;
        DB_PATH = File.separator + "data"
                + Environment.getDataDirectory().getAbsolutePath() + File.separator
                + context.getPackageName() + File.separator + "databases" + File.separator;
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    public void copyDBFile() {
        File dir = new File(DB_PATH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File dbFile = new File(DB_PATH + DB_NAME);
        if (!dbFile.exists()) {//TODO 这里注意判断db版本号，如果版本号不一致也需要复制进去
            InputStream is;
            OutputStream os;
            try {
                is = mContext.getResources().getAssets().open(ASSETS_NAME);
                os = new FileOutputStream(dbFile);
                byte[] buffer = new byte[BUFFER_SIZE];
                int length;
                while ((length = is.read(buffer, 0, buffer.length)) > 0) {
                    os.write(buffer, 0, length);
                }
                os.flush();
                os.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据parentId查询子地址，第一级parentId为0
     *
     * @param parentId
     * @param isNetworkPointQuery true:网点查询,需要根据wdflag过滤
     * @return
     */
    public List<City> getCitiesByParentId(String parentId,boolean isNetworkPointQuery) {
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH + DB_NAME, null);
        String where = PARENTID + " = " + parentId;
        if (isNetworkPointQuery){
            where+= " and "+WDFLAG+" = 1";
        }
        Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " where " + where, null);
        List<City> result = new ArrayList<>();
        City city;
        while (cursor.moveToNext()) {
            city = setUpCityByCursor(cursor);
            result.add(city);
        }
        cursor.close();
        db.close();
        Collections.sort(result, new CityComparator());
        return result;
    }

    public List<City> searchCity(final String keyword) {
        SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH + DB_NAME, null);
        Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " where " + FULLNAME + " like \"%" + keyword
                + "%\" or " + FULLPY + " like \"%" + keyword + "%\"", null);
        List<City> result = new ArrayList<>();
        City city;
        while (cursor.moveToNext()) {
            city = setUpCityByCursor(cursor);
            result.add(city);
        }
        cursor.close();
        db.close();
        Collections.sort(result, new CityComparator());
        return result;
    }

    private City setUpCityByCursor(Cursor cursor) {
        String uniqueid = cursor.getString(cursor.getColumnIndex(UNIQUEID));
        String fullName = cursor.getString(cursor.getColumnIndex(FULLNAME));
        String fullpy = cursor.getString(cursor.getColumnIndex(FULLPY));
        String startpy = cursor.getString(cursor.getColumnIndex(STARTPY));
        String parentid = cursor.getString(cursor.getColumnIndex(PARENTID));
        String leveltype = cursor.getString(cursor.getColumnIndex(LEVELTYPE));
        String status = cursor.getString(cursor.getColumnIndex(STATUS));
        String flag = cursor.getString(cursor.getColumnIndex(FLAG));
        String wdflag = cursor.getString(cursor.getColumnIndex(WDFLAG));
        String allflag = cursor.getString(cursor.getColumnIndex(ALLFLAG));
        City city = new City(uniqueid, fullName, fullpy, startpy, parentid, leveltype, status, flag, wdflag, allflag);
        return city;
    }

    /**
     * sort by a-z
     */
    private class CityComparator implements Comparator<City> {
        @Override
        public int compare(City lhs, City rhs) {
            String a = lhs.getFullPY().substring(0, 1);
            String b = rhs.getFullPY().substring(0, 1);
            return a.compareTo(b);
        }
    }
}
